package blog

import (
	"github.com/astaxie/beego/orm"
	"time"
)

// 公告
type Notice struct {
	Id      int
	Title   string `orm:"size(128)"`
	Content string `orm:"type(text)"`
	Default bool
	StartAt time.Time `orm:"type(datetime)"`
	EndAt   time.Time `orm:"type(datetime)"`
}

func (o *Notice) TableName() string {
	return "blog_notices"
}

func CreateNotice(title, content string, startAt, endAt time.Time) error {
	notice := Notice{Title: title, Content: content, StartAt: startAt, EndAt: endAt}
	_, err := orm.NewOrm().Insert(&notice)
	return err
}

func UpdateNotice(id int, title, content string, startAt, endAt time.Time) error {
	notice := Notice{Id: id}
	err := orm.NewOrm().Read(&notice)
	if err != nil {
		return err
	}
	notice.Title = title
	notice.Content = content
	notice.StartAt = startAt
	notice.EndAt = endAt
	_, err = orm.NewOrm().Update(&notice)
	return err
}

func SetDefaultNotice(id int) error {
	notice := Notice{Id: id}
	err := orm.NewOrm().Read(&notice)
	if err != nil {
		return err
	}
	notice.Default = true
	_, err = orm.NewOrm().QueryTable(new(Notice)).Update(orm.Params{"default": false})
	if err != nil {
		return err
	}
	_, err = orm.NewOrm().Update(&notice)
	return err
}

func GetNoticePaginator(limit, page int) (all []Notice, total int64, err error) {
	if limit == 0 {
		limit = 10
	}
	if page == 0 {
		page = 1
	}
	qs := orm.NewOrm().QueryTable(new(Notice))
	total, _ = qs.Count()
	_, err = qs.Offset((page - 1) * limit).Limit(limit).All(&all)
	return
}

func GetNoticeFromId(id int) (Notice, error) {
	var err error
	notice := Notice{Id: id}
	_ = orm.NewOrm().Read(&notice)
	return notice, err
}

func GetDefaultNotice() (Notice, error) {
	var err error
	timeNow := time.Now()
	notice := Notice{}
	qs := orm.NewOrm().QueryTable(new(Notice))

	if c, _ := qs.Filter("start_at__lte", timeNow).Filter("end_at__gte", timeNow).Count(); c == 0 {
		err = qs.Filter("default", true).One(&notice)
	} else {
		err = qs.Filter("start_at__lte", timeNow).Filter("end_at__gte", timeNow).One(&notice)
	}

	return notice, err
}
